package com.next

import grails.gorm.transactions.Transactional
import org.springframework.security.access.annotation.Secured

import static org.springframework.http.HttpStatus.*

/**
 * @Author 班旭娟* @ModifiedDate 2017-4-21
 */
@Secured(['ROLE_ADMINISTRATOR', 'ROLE_HEAD_OFFICE_ADMINISTRATOR', 'ROLE_PROVINCE_BRANCH_OFFICE_ADMINISTRATOR', 'ROLE_PROVINCE_BRANCH_OFFICE_PRODUCT_MANAGER', 'ROLE_SECOND_BRANCH_OFFICE_PRODUCT_MANAGER',
    'ROLE_SECOND_BRANCH_OFFICE_DIRECTOR', 'ROLE_ACCOUNT_MANAGER', 'ROLE_SALES_REPRESENTATIVE', 'ROLE_BANK_OUTLETS_ADMINISTRATOR', 'ROLE_MERCHANT_ADMINISTRATOR', 'ROLE_CHANNEL_ADMINISTRATOR'])
@Transactional(readOnly = true)
class TerritoryController
{

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def index(Integer max)
    {
        //        params.max = Math.min(max ?: 10, 100)
        def offset = params.offset
        params.max = 10
        params.offset = params.offset ? params.offset.toInteger() : 0
        max = 10
        def list = Territory.findAll("from Territory where level = 0", [max: max, offset: offset])
        def count = Territory.findAllByLevel(0)?.size()
        respond list, model: [territoryCount: count]
    }

    def show(Territory territory)
    {
        def territoryAccounts = TerritoryAccount.findAllByTerritory(territory)
        def territoryProducts = TerritoryProduct.findAllByTerritory(territory)
        def territoryCities = TerritoryCity.findAllByTerritory(territory)
        def territoryTeams = TerritoryTeam.findAllByTerritory(territory)

        def territoryFlexFieldCategories = TerritoryFlexFieldCategory.findAllByTerritory(territory)
        def subTerritories = Territory.findAllByParent(territory)
        def territoryWorkflows = TerritoryWorkflow.findAllByTerritory(territory)
        respond territory, model: [territoryAccounts: territoryAccounts, territoryProducts: territoryProducts,
            territoryCities: territoryCities, territoryTeams: territoryTeams,
            territoryFlexFieldCategories: territoryFlexFieldCategories, subTerritories: subTerritories, territoryWorkflows: territoryWorkflows]

    }

    def create()
    {
        respond new Territory(params)
    }

    @Transactional
    def save(Territory territory)
    {
        if (territory == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (territory.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond territory.errors, view: 'create'
            return
        }

        if (territory.inheritTeam)
        {
            if (!territory?.parent)
            {
                flash.message = message(code: 'territory.parent.nullable.message')
                respond territory.errors, view: 'create'
                return
            }
        }

        territory.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'territory.label',
                                                                                        default: 'Territory'),
                    territory.id])
                redirect territory
            }
            '*' { respond territory, [status: CREATED] }
        }
    }

    def edit(Territory territory)
    {
        respond territory
    }

    @Transactional
    def update(Territory territory)
    {
        if (territory == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (territory.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond territory.errors, view: 'edit'
            return
        }

        //旧流程
        if (territory.inheritTeam)
        {
            if (!territory?.parent)
            {
                flash.message = message(code: 'territory.parent.nullable.message')
                respond territory.errors, view: 'create'
                return
            }
        }
        //新流程
        if (territory.inheritTeam)
        {
            if (!territory?.parent)
            {
                flash.message = message(code: 'territory.parent.nullable.message')
                respond territory.errors, view: 'create'
                return
            }
        }

        territory.save flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'territory.label',
                                                                                        default: 'Territory'),
                    territory.id])
                redirect territory
            }
            '*' { respond territory, [status: OK] }
        }
    }

    @Transactional
    def delete(Territory territory)
    {

        if (territory == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        territory.delete flush: true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'territory.label',
                                                                                        default: 'Territory'),
                    territory.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NO_CONTENT }
        }
    }

    protected void notFound()
    {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'territory.label',
                                                                                          default: 'Territory'),
                    params.id])
                redirect action: "index", method: "GET"
            }
            '*' { render status: NOT_FOUND }
        }
    }

    def searchTerritory()
    {
        params.max = Math.min(params.max ? params.max.toInteger() : 10, 100)
        params.offset = params.offset ? params.offset.toInteger() : 0

        def max = params.max
        def offset = params.offset
        def name = params['name']
        def territoryList = Territory.findAll("from Territory where name like '%${name}%'", [max: max, offset: offset])
        def list = Territory.findAll("from Territory where name like '%${name}%'")
        def count = list.size()

        respond territoryList, model: [territoryCount: count], view: 'index'
    }

}
